//
//  PriceViewController.swift
//  Automobile
//
//  Created by erkebulan elzhan on 8/19/20.
//  Copyright © 2020 erkebulan elzhan. All rights reserved.
//

import UIKit

final class PriceViewController: UIViewController, Alertable {
    
    enum AveragePriceState {
        case loading
        case error
        case success (Int)
    }
    
    // MARK: - Outlets
    
     private lazy var submitBtn: UIButton = {
        let btn = UIButton()
        btn.clipsToBounds = true
        btn.layer.cornerRadius = 15
        btn.setTitle("Далее", for: .normal)
        btn.backgroundColor = .blueColor
        btn.setTitleColor(.white, for: .normal)
        btn.titleLabel!.font = UIFont.systemFont(ofSize: 17, weight: .medium)
        return btn
    }()
    
    private lazy var hintLbl: UILabel = {
        let lbl = UILabel()
        lbl.font = .systemFont(ofSize: 12)
        lbl.textColor = .darkBlueColor
        lbl.sizeToFit()
        lbl.text = "Средняя цена"
        return lbl
    }()
    
    private lazy var priceLbl: UILabel = {
        let lbl = UILabel()
        lbl.font = .systemFont(ofSize: 12)
        lbl.textColor = .darkBlueColor
        lbl.sizeToFit()
        lbl.text = "Загружается ..."
        return lbl
    }()
    
    private lazy var priceBtn: ModalElement = {
        let element = ModalElement()
        element.updateUI(value: nil, placeholder: "Цена", withTF: true, keyboardType: .numberPad)
        return element
    }()
    
    private lazy var obmenToggle: ToggleView = {
        let toggle = ToggleView()
        toggle.makeToggleView(name: "Возможен обмен", isOn: true)
        return toggle
    }()
    
    private lazy var rastomozhenToggle: ToggleView = {
        let toggle = ToggleView()
        toggle.makeToggleView(name: "Растаможен", isOn: false)
        return toggle
    }()
    

    // MARK: - Props

    public weak var delegate: AdCreatorProtocol!
    
    @Price private var templateTxt = ""
    private var avergePrice: AveragePriceState = .loading {
        didSet {
            switch avergePrice {
            case .loading:
                self.priceLbl.text = "Загружается ..."
            case .error:
                self.priceLbl.text = "Неизвестно"
                self.priceLbl.textColor = .red
            case .success(let price):
                templateTxt = "\(price)"
                self.priceLbl.text = templateTxt
                self.priceLbl.textColor = .blueColor
            }
        }
    }
    private var vin: String = ""
    
    
    // MARK: - UI Actions
    
    @objc private func goBack (sender: UIBarButtonItem) {
        self.navigationController?.popViewController(animated: true)
    }
    
    @objc private func closeVC (sender: UIBarButtonItem) {
        self.navigationController?.dismiss(animated: true, completion: nil)
        delegate.removeEverything()
    }
    
    @objc private func onSubmit (sender: UIButton) {
        
        if let price = Int(priceBtn.getTextFieldValue()) {
            delegate.getPrice(price: price, isObmen: obmenToggle.isOn(), isRastomozhen: rastomozhenToggle.isOn())
            self.navigationController?.dismiss(animated: true, completion: nil)
            delegate.showAdPreview()
        } else {
            self.showAlert("Упс...", "Введите цену")
        }

    }
   
    @objc private func screenTap (sender: UITapGestureRecognizer) {
        self.priceBtn.closeTextField()
    }
    

    // MARK: - Life-Cycle
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.vin = delegate.giveStateNumber()
        loadAveragePrice()
        self.setUpUI()
        self.setUpNavBar()
    }

}

// MARK: - Methods


extension PriceViewController {
    private func loadAveragePrice () {
        let request = URLRequest(url: Request(base: .garage).getUrl(path: "checkauto/average_price/\(self.vin)/"))
        let dataTask = URLSession.shared.dataTask(with: request) { (data, _, _) in
            DispatchQueue.main.async {
                guard let jsonData = data else {
                    self.avergePrice = .error
                    return
                }
                
                if let data = try? JSONSerialization.jsonObject(with: jsonData, options: []) {
                    if let price = (data as? [String: Any])?["average_price"] as? Int {
                        self.avergePrice = .success(price)
                    } else {
                        print("ERROR [data]", data)
                        self.avergePrice = .error
                    }
                } else {
                    self.avergePrice = .error
                }
            }
        }
        dataTask.resume()
    }
}


// MARK: - UI

extension PriceViewController {
    
    private func setUpUI () {
        view.backgroundColor = .white
        view.addSubview(priceBtn)
        view.addSubview(obmenToggle)
        view.addSubview(rastomozhenToggle)
        view.addSubview(submitBtn)
        view.addSubview(hintLbl)
        view.addSubview(priceLbl)
        
        
        self.addCloseIcon()
        self.addConstraints()
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(screenTap(sender:)))
        self.view.addGestureRecognizer(tapGesture)
        submitBtn.addTarget(self, action: #selector(onSubmit(sender:)), for: .touchUpInside)
    }
    
    private func addConstraints () {
        priceBtn.snp.makeConstraints { (make) in
            make.top.equalTo(view.safeAreaLayoutGuide).offset(30)
            make.leading.trailing.equalToSuperview().inset(16)
            make.height.equalTo(48)
        }
        obmenToggle.snp.makeConstraints { (make) in
            make.top.equalTo(priceBtn.snp.bottom).offset(24)
            make.leading.trailing.equalToSuperview().inset(16)
            make.height.equalTo(64)
        }
        rastomozhenToggle.snp.makeConstraints { (make) in
            make.top.equalTo(obmenToggle.snp.bottom).offset(24)
            make.leading.trailing.equalToSuperview().inset(16)
            make.height.equalTo(64)
        }
        hintLbl.snp.makeConstraints { (make) in
            make.leading.equalToSuperview().offset(16)
            make.top.equalTo(rastomozhenToggle.snp.bottom).offset(24)
            make.height.equalTo(16)
        }
        priceLbl.snp.makeConstraints { (make) in
            make.top.equalTo(rastomozhenToggle.snp.bottom).offset(24)
            make.height.equalTo(16)
            make.leading.equalTo(hintLbl.snp.trailing).offset(8)
        }
        submitBtn.snp.makeConstraints { (make) in
            make.leading.trailing.equalToSuperview().inset(16)
            make.bottom.equalTo(view.safeAreaLayoutGuide).offset(-16)
            make.height.equalTo(44)
        }
    }
    
    private func setUpNavBar () {
        let backIcon = UIImage(named: "cancel")
        let backButton = UIBarButtonItem(image: backIcon, landscapeImagePhone: backIcon, style: .plain, target: self, action: #selector(goBack(sender:)))
        backButton.tintColor = .greyColor
        
        self.navigationItem.simpleNavBar(title: "Цена", backButton: backButton)
        navigationItem.largeTitleDisplayMode = .always
        navigationController?.navigationBar.largeTitleTextAttributes = [
            NSAttributedString.Key.font: UIFont.systemFont(ofSize: 24, weight: .bold)
        ]
        navigationItem.hidesSearchBarWhenScrolling = false
        self.navigationController?.navigationItem.largeTitleDisplayMode = .always
    }

    private func addCloseIcon () {
        let closeBarBnt = UIBarButtonItem(image: UIImage(named: "dismiss"), style: .plain, target: self, action: #selector(closeVC))
        closeBarBnt.tintColor = .greyColor
        self.navigationItem.rightBarButtonItem = closeBarBnt
    }
}

